﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace Domain
{
    public class Executor
    {
        private const string expressionFileName = "expression.txt";
        private const string argumentsFileName = "arguments.txt";

        private const string reductorFileName = "reductor.exe";

        private const string logsFileName = "log.txt";
        private const string resultFileName = "result.txt";

        public Dictionary<OutputStrings, string> Execute(Dictionary<InputStrings, string> input)
        {
            writeToFile(input[InputStrings.expresion], expressionFileName);
            writeToFile(input[InputStrings.args], argumentsFileName);

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = reductorFileName;
            startInfo.Arguments = expressionFileName + " " + argumentsFileName;
            var reductionProcess = Process.Start(startInfo);
            reductionProcess.WaitForExit();

            var result = new Dictionary<OutputStrings, string>();
            try
            {
                result.Add(OutputStrings.result, readResultFromFIle(resultFileName));
                result.Add(OutputStrings.log, readResultFromFIle(logsFileName));
            }
            catch (Exception e)
            {
                File.Delete(expressionFileName);
                File.Delete(argumentsFileName);
                throw new Exception("error while reading");
            }

            File.Delete(expressionFileName);
            File.Delete(argumentsFileName);
            File.Delete(logsFileName);
            File.Delete(resultFileName);

            return result;

        }

        private void writeToFile(string toWrite, string fileName)
        {
            using (StreamWriter outfile = new StreamWriter(fileName))
            {
                outfile.Write(toWrite);
            }
        }


        private string readResultFromFIle(string filename)
        {
            StringBuilder result = new StringBuilder();
            using (StreamReader sr = new StreamReader(filename))
            {
                result.Append(sr.ReadToEnd());
            }
            return result.ToString();
        }





    }
}
